<template>
  <div class="enter-account">
    <div class="content-title">
      <span class="editPassword">{{ $t("module.userCenter.setPassword") }}</span>
      <Icon class="editIcon" @click="editPassword" type="ios-close" size="40" />
    </div>
    <div class="content-main">
      <!-- <div class="hint">{{ $t("module.userCenter.character") }}</div> -->
      <!-- <div class="hint">8-20位字符，至少包含字母、数字、特殊字符中的两种</div> -->
      <Form :model="modelForm" ref="editForm" class="ivu-form-no-margin-bottom" :rules="rule" :label-width="0">
        <div class="div-container">
          <div style="width:400px">
            <Form-item prop="password1">
              <Input
                type="password"
                v-model="modelForm.password1"
                :placeholder="$t('module.userCenter.enterPassword')"
                size="large"
                :maxlength="20"
              />
            </Form-item>
            <FormItem prop="password2">
              <Input
                type="password"
                v-model="modelForm.password2"
                :placeholder="$t('module.userCenter.repeatPassword')"
                size="large"
                :maxlength="20"
              />
            </FormItem>
          </div>
          <div class="vertical"></div>
          <div style="width:400px">
            <Row class="code-row-bg strategy">
              <Col class="ask" span="24" style="border:none;">{{  $t('module.userCenter.passwordStrategyTitle' )}}</Col>
              <Col class="ask" span="24" style="border:none;">{{ $t('module.userCenter.passwordStrategy1')}}</Col>
              <Col span="24" style="border:none;">{{ $t('module.userCenter.passwordStrategy2')}}</Col>
              <Col span="24" style="border:none;">{{ $t('module.userCenter.passwordStrategy3')}}</Col>
            </Row>
          </div>
        </div>
        <div class="div-bottom">
          <div class="button">
            <RPButton
              optType="confirm"
              style="width: 20%; borderradius: 0; height: 34px;"
              size="large"
              @click="save"
              :disabled="isSuccess"
            />
            <RPButton
              size="large"
              optType="text"
              style="width: 20%; borderradius: 0; height: 34px;"
              @click="editPassword"
              :text="$t('module.userCenter.cancel')"
            />
          </div>
        </div>
      </Form>
    </div>
  </div>
</template>
<script>
import userCenter from "@lang/modules/userCenter";
import { JSEncrypt } from "jsencrypt";
export default {
  name: "change-password",
  components: {},
  locales: {
    "zh-CN": {
      module: {
        userCenter: userCenter["zh-CN"]
      }
    },
    "en-US": {
      module: {
        userCenter: userCenter["en-US"]
      }
    }
  },
  props: {},
  data() {
    // const validatePassword1 = (rule, value, callback) => {
    //   if (value === "") {
    //     callback(new Error(this.$t("module.userCenter.enterPassword")));
    //   } else if (value.length < 8) {
    //     callback(new Error(this.$t("module.userCenter.passwordNumber")));
    //   }
    //   callback();
    // };
    const validatePassword1 = (rule, value, callback) => {
      let regSign = /^[\x00-\xff]*$/;
      if (value === "") {
        callback(new Error(this.$t("module.userCenter.enterNewPassword")));
      } else if (value.length < 8 || value.length > 20) {
        callback(new Error(this.$t("module.userCenter.formatPassword")));
      } else if (!regSign.test(value)) {
        callback(new Error(this.$t("module.userCenter.InvaildSymbol")));
      } else if (
        !new RegExp(
          "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[-$\\]~(^{\\\\+|/_:})=@\\[;',<`\">.!%*#?&])[A-Za-z\\d-$\\]~(^{\\\\+|/_:})=@\\[;',<`\">.!%*#?&]{8,}$"
        ).test(value)
      ) {
        callback(new Error(this.$t("module.userCenter.complexPassword")));
      }
      callback();
    };

    const validatePassword2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.userCenter.repeatPassword")));
      } else if (value != this.modelForm.password1) {
        callback(new Error(this.$t("module.userCenter.secondPassword")));
      }
      callback();
    };
    return {
      modelForm: {
        account: "",
        captcha: "",
        password1: "",
        password2: "",
        tenant: null
      },
      rule: {
        password1: [{ validator: validatePassword1, trigger: "blur", required: true }],
        password2: [{ validator: validatePassword2, trigger: "blur", required: true }]
      },
      isSuccess: false
    };
  },
  computed: {},
  created: function() {
    // console.log(this.$route.params);
    this.init(this.$route.params);
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    init(params) {
      this.modelForm.account = params.account;
      this.modelForm.captcha = params.captcha;
      this.modelForm.tenant = params.tenant;
    },
    rasEncryptPwd(publicKey, password) {
      let encrypt = new JSEncrypt();
      encrypt.setPublicKey(publicKey);
      let data = encrypt.encrypt(password);
      return data;
    },
    save() {
      const modelForm = {
        account: this.modelForm.account,
        verificationCode: this.modelForm.captcha,
        userPwd: this.modelForm.password1,
        confirmPwd: this.modelForm.password2,
        tenant: this.modelForm.tenant
      };
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          $http.get(`${window.RPConfig.mgt}/security/getPublicKey`).then(({ data }) => {
            let params = modelForm;
            params.userPwd = this.rasEncryptPwd(data, modelForm.userPwd);
            params.confirmPwd = this.rasEncryptPwd(data, modelForm.confirmPwd);
            window.$http
              .post(`${window.RPConfig.userCenter}/user/resetPassword?tenant=` + this.modelForm.tenant, params)
              .then(({ data }) => {
                if (data) {
                  this.$message.success({
                    content: this.$t("module.userCenter.resetSuccess"),
                    duration: 3
                  });
                }
                this.editPassword();
              })
              .catch(() => {
                this.isLoading = false;
              });
          });
        }
      });
    },
    editPassword() {
      const type = window.RPConfig.logintype;
      if (type === "cas") {
        window.location.href = window.RPConfig.cas_logout + "?service=" + window.location.origin;
      } else if (type === "single") {
        this.$router.push({ path: "/login" });
      } else {
        window?.$util?.redirectToLogin()
      }
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less" scoped>
@import "./forgotPassword.less";

.div-container{
  display: flex;
  justify-content: space-between;
  align-items: center;

  .strategy{
    margin-left: 20px;
    font-size: 12px;
    color: #515a6e;

    .ask{
      margin-top: 10px;
    }
  }

  .vertical{
    height: 140px;
    width: 1px;
    margin-left: 20px;
    background: #d8d8d8;
  }
}



.div-bottom{
  width: 100%;
  .button{
    display: flex;
    justify-content: end;
  }

}

</style>
